package cn.edu.sdjzu.xg.kcsj.controller.basic;

import cn.edu.sdjzu.xg.kcsj.domain.Course;
import cn.edu.sdjzu.xg.kcsj.service.CourseService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/selectCourse.ctl")
public class SelectCourseController extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        JSONObject respMessage = new JSONObject ();
        resp.setContentType ("application/json;charset=UTF-8");
        String id_str = req.getParameter ("id");
        if (id_str == null) {
            respMessage.put ("message","no have request");
            resp.getWriter ().println (respMessage);
        } else {
            int id_int = Integer.parseInt (id_str);
            try {
                responseCourse (id_int,resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace ();
            }
        }
    }
    @Override
    protected void doPost (HttpServletRequest req,HttpServletResponse resp) {
        JSONObject respMessage_jsonObj = new JSONObject();
        resp.setContentType("application/json;charset=UTF-8");
        try {
            this.responseCourse(resp);
        } catch (SQLException e) {
            respMessage_jsonObj.put ("message","sjk have exception");
        } catch (ServletException e) {
            respMessage_jsonObj.put ("message","ServletException");
        } catch (IOException e) {
            respMessage_jsonObj.put ("message","IOException");
        }
    }
    private void responseCourse(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        Collection<Course> courses = CourseService.getInstance().findAll();
        String students_jsonStr = JSON.toJSONString(courses,
                SerializerFeature.DisableCircularReferenceDetect);
        JSONObject resp_jsonObj = new JSONObject();
        resp_jsonObj.put("data", students_jsonStr);
        response.getWriter().println(resp_jsonObj);
    }

    private void responseCourse (int id_int,HttpServletResponse resp) throws IOException, SQLException {
        Course course = CourseService.getInstance ().find (id_int);
        String course_jsonStr = JSON.toJSONString (course,SerializerFeature.DisableCircularReferenceDetect);
        resp.getWriter ().println (course_jsonStr);
    }
}
